package com.shop.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.shop.Redis.GoodsKey;
import com.shop.Redis.RedisService;
import com.shop.dao.GoodsAttrValsMapper;
import com.shop.dao.GoodsMapper;
import com.shop.pojo.*;
import com.shop.service.GoodsService;
import com.shop.util.BaseUtil;
import com.sun.org.apache.xpath.internal.operations.Bool;
import net.sf.json.JSONArray;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

@Service
public class GoodsServiceImpl implements GoodsService {
    @Resource
    private GoodsMapper goodsMapper;
    @Resource
    private GoodsAttrValsMapper goodsAttrValsMapper;
    @Resource
    private RedisService redisService;
    @Autowired
    private MongoTemplate mongoTemplate;

    /*定义集合名称*/
    private static final String collectionName = "goods";

    @Override
    public List<Goods> selectAll() {
        return goodsMapper.selectAll();
    }

    /*商品全局搜索*/
    @Override
    public Map<String,Object> queryGoodsByCondition(Map<String,Object> params) {
        Map<String,Object> dataParams = new HashMap<>();
        List<Goods> goodsList = null;

        //获取当前页面的分页信息，pageIndex为当前页号，dataCol为数据显示的数量
        int pageIndex = params.get("pageIndex") != null ? Integer.parseInt(params.get("pageIndex").toString()) : 1;
        int dataCol = params.get("dataCol") != null ? Integer.parseInt(params.get("dataCol").toString()) : 10;

//        //设置分页查询的数据量
//        params.put("pageIndex",(pageIndex - 1) * dataCol);
//        params.put("dataCol",dataCol);
//
//        //查询数据
//        goodsList = goodsMapper.queryGoodsByCondition(params);
//        for(Goods goods : goodsList){
//            goods.setPrice((Math.random() * (1000-100+1))+5);
//        }
//        redisService.set(GoodsKey.getGoodsTotal,"Total",String.valueOf(goodsList.size()));
//        dataParams.put("data",goodsList);
//
//        //获取redis中的数据总量，并返回给前端进行渲染
//        int total = redisService.get(GoodsKey.getGoodsTotal,"Total",Integer.class);
//        dataParams.put("total",total);

        Query query = new Query();
        if (pageIndex != 1) {
            // number 参数是为了查上一页的最后一条数据
            int number = (pageIndex - 1) * dataCol;
            query.limit(number);

            goodsList = mongoTemplate.find(query, Goods.class,collectionName);
            // 取出最后一条
            Goods goods = goodsList.get(goodsList.size() - 1);

            // 取到上一页的最后一条数据 id，当作条件查接下来的数据
            String id = goods.getGoodsId();

            // 从上一页最后一条开始查（大于不包括这一条）
            query.addCriteria(Criteria.where("_id").gt(id));
        }
        // 页大小重新赋值，覆盖 number 参数
        query.limit(dataCol);

        for (Map.Entry<String,Object> map : params.entrySet()) {
            query.addCriteria(Criteria.where(map.getKey()).is(map.getValue()));
        }

        goodsList = mongoTemplate.find(query, Goods.class,collectionName);
        dataParams.put("data",goodsList);

        int total = goodsList.size();
        dataParams.put("total",total);

        return dataParams;
    }

    /*商品详细查询*/
    @Override
    public Map<String,Object> getGoodsDetailByGoodsId(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String goodsId = request.getParameter("goodsId");
        Map<String,Object> dataMap = new HashMap<>();

        /*先从redis中获取商品缓存数据，如果没有的话则调用数据库查询*/
        Map<String,Object> dataRedisMap = redisService.get(GoodsKey.getGoodsDetail,goodsId,Map.class);
        if(dataRedisMap != null){
            return dataRedisMap;
        }

        Goods goods = goodsMapper.selectByPrimaryKey(goodsId);
        List<GoodsAttrVals> goodsAttrVals = goodsAttrValsMapper.selectByGoodsId(goodsId);
        dataMap.put("goods",goods);
        dataMap.put("attrVals",goodsAttrVals);

        /*放入redis中作为缓存，提高速度*/
        redisService.set(GoodsKey.getGoodsDetail,goodsId,dataMap);
        return dataMap;
    }

    /*添加商品接口*/
    @Override
    public String addGood(HttpServletRequest request, HttpServletResponse response) throws Exception{
        String data = request.getParameter("data");
        data = BaseUtil.dataTranscoding(data);

        JSONArray jsonArray = JSONArray.fromObject(data);
        List<Goods> goodsLists = new ArrayList<>();
        List<GoodsAttrVals> goodsAttrValsLists = new ArrayList<>();

        for (int i = 0, l = jsonArray.size(); i < l; i++) {
            String json = BaseUtil.toJson(jsonArray.get(i));
            Map<String,Object> params = BaseUtil.json2Map(json);

            Goods goods = JSONObject.parseObject(json, Goods.class);
            goods.setGoodsId(BaseUtil.getSID());
            goods.setgoodsTag("面膜");

            JSONArray jsonArrayAttr = JSONArray.fromObject(params.get("goodsAttrVals").toString());
            for (int j = 0, k = jsonArray.size(); j < k; j++) {
                String jsonAttr = BaseUtil.toJson(jsonArrayAttr.get(j));

                GoodsAttrVals goodsAttrVals = JSONObject.parseObject(jsonAttr, GoodsAttrVals.class);
                goodsAttrVals.setAttrValsId(BaseUtil.getSID());
                goodsAttrVals.setGoodsId(goods.getGoodsId());
                goodsAttrVals.setCreateTime(new Date());
                goodsAttrValsLists.add(goodsAttrVals);
            }

            goods.setCreateTime(new Date());
            goodsLists.add(goods);
        }

        /*MySQL操作*/
//        for(Goods good : goodsLists){
//            goodsMapper.insert(good);
//        }
//
//        for(GoodsAttrVals goodsAttrVals : goodsAttrValsLists){
//            goodsAttrValsMapper.insert(goodsAttrVals);
//        }

        /*MongoDB操作*/
        for(Goods good : goodsLists){
            mongoTemplate.insert(good,collectionName);
        }

        for(GoodsAttrVals goodsAttrVals : goodsAttrValsLists){
            mongoTemplate.insert(goodsAttrVals,"goodsAttrVals");
        }

        return "添加商品成功";
    }

    /*根据商品ID添加商品规格*/
    @Override
    public String addGoodAttrVals(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String data = request.getParameter("data");
        String goodsId = request.getParameter("goodsId");
        String json = BaseUtil.toJson(data);
        GoodsAttrVals goodsAttrVals = JSONObject.parseObject(json,GoodsAttrVals.class);

        goodsAttrVals.setAttrValsId(BaseUtil.getSID());
        goodsAttrVals.setGoodsId(goodsId);

        /*MySQL操作*/
//        goodsAttrValsMapper.insert(goodsAttrVals);

        /*MongoDB操作*/
        mongoTemplate.insert(goodsAttrVals,"goodsAttrVals");

        return "添加商品规格成功";
    }

    /*修改商品信息*/
    @Override
    public String editGood(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String goodsData = request.getParameter("goodsData");
        goodsData = BaseUtil.dataTranscoding(goodsData);

        Map<String,Object> goodsDataParams = BaseUtil.json2Map(goodsData);
        goodsDataParams.put("updateTime",new Date());

        /*MySQL操作*/
//        goodsMapper.updateGoodsByCondition(goodsDataParams);

        /*MongoDB操作*/
        Query query = new Query();
        query.addCriteria(Criteria.where("goodsId").is(goodsDataParams.get("goodsId").toString()));
        Update goodsUpdate = new Update();
        for (Map.Entry<String,Object> map : goodsDataParams.entrySet()) {
            goodsUpdate.set(map.getKey(),map.getValue());
        }
        mongoTemplate.updateMulti(query,goodsUpdate,collectionName);


        String attrValsData = request.getParameter("attrValsData");
        if(StringUtils.isNotEmpty(attrValsData)){
            attrValsData = BaseUtil.dataTranscoding(attrValsData);

            Map<String,Object> attrValsDataParams = BaseUtil.json2Map(attrValsData);
            attrValsDataParams.put("updateTime",new Date());

            /*MySQL操作*/
//            goodsAttrValsMapper.updateGoodsAttrValsByCondition(attrValsDataParams);

            /*MongoDB操作*/
            Update goodsAttrUpdate = new Update();
            for (Map.Entry<String,Object> map : attrValsDataParams.entrySet()) {
                goodsAttrUpdate.set(map.getKey(),map.getValue());
            }
            mongoTemplate.updateMulti(query,goodsAttrUpdate,"goodsAttrVals");

        }

        return "修改商品成功";

    }

    /*删除商品*/
    @Override
    public String deleteGood(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String goodsId = request.getParameter("goodsId");
        if(StringUtils.isNotEmpty(goodsId)){

            /*MySQL操作*/
//            goodsAttrValsMapper.deleteAttrByGoodsId(goodsId);
//            goodsMapper.deleteByPrimaryKey(goodsId);

            /*MongoDB操作*/
            Query query = new Query();
            query.addCriteria(Criteria.where("goodsId").is(goodsId));   //goodsId作为删除的限制条件

            mongoTemplate.remove(query, Goods.class,collectionName);
            mongoTemplate.remove(query, GoodsAttrVals.class,"goodsAttrVals");

            return "删除商品成功";
        }

        return "删除商品失败，该商品ID不存在，请重试";
    }

    /*商品热销查询*/
    @Override
    public List<Goods> getGoodsSaleByCondition(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String data = request.getParameter("data");
        Map<String,Object> params = null;
        if (StringUtils.isNotEmpty(data)){
            params = BaseUtil.json2Map(data);
        }else{
            params = new HashMap<>();
        }

        List<Goods> goodsList = new ArrayList<>();

        /*MySQL操作*/
        goodsList = goodsMapper.getGoodsSaleByCondition(params);

        /*MongoDB操作*/
//        Query query = new Query();
//        query.fields().exclude("_id");
////        query.fields().include(collectionName);   //指定只返回的key对应value值
//
//        for (Map.Entry<String,Object> map : params.entrySet()) {
//            query.addCriteria(Criteria.where(map.getKey()).is(map.getValue()));
//        }
//
//        goodsList = mongoTemplate.find(query, Goods.class,collectionName);

        return goodsList;
    }


}
